package com.mobile.resources;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

/**
 * http://localhost:8080/rest/rest/helloworld?name=asdf
 */
@Path("/helloworld")
public class HelloWorld {
	/**
	 * 获取资源
	 */
	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public String getResult(@QueryParam("name") String name) {
		System.out.println("==============getResult");
		return result(name);
	}

	/**
	 * 创建资源
	 */
	@POST
	@Produces(MediaType.TEXT_PLAIN)
	public String postResult(@QueryParam("name") String name) {
		System.out.println("==============postResult");
		return result(name);
	}

	/**
	 * 修改资源
	 */
	@PUT
	@Produces(MediaType.TEXT_PLAIN)
	public String putResult(@QueryParam("name") String name) {
		System.out.println("==============putResult");
		return result(name);
	}

	/**
	 * 删除资源
	 */
	@DELETE
	@Produces(MediaType.TEXT_PLAIN)
	public String delResult(@QueryParam("name") String name) {
		System.out.println("==============delResult");
		return result(name);
	}

	private String result(String name) {
		return name + ", hello";
	}

	private static final String targetURL = "http://localhost:8080/rest/rest/helloworld?name=test";

	public static void main(String[] args) {
		try {
			URL targetUrl = new URL(targetURL);
			HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod("PUT");
			httpConnection.setRequestProperty("Content-Type", "application/json");

			//			String input = "name=test";
			//			OutputStream outputStream = httpConnection.getOutputStream();
			//			outputStream.write(input.getBytes());
			//			outputStream.flush();

			if (httpConnection.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : " + httpConnection.getResponseCode());
			}
			BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));
			String output;
			System.out.println("Output from Server:\n");
			while ((output = responseBuffer.readLine()) != null) {
				System.out.println(output);
			}
			httpConnection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
